#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/fcntl.h>
#include <unistd.h>
#include "Error.hpp"
#include "Log.hpp"

class SockTCP
{
    const static int default_backlog = 5;
    const static int default_fd = -1;

public:
    SockTCP()
        : _sockfd(default_fd)
    {
    }
    ~SockTCP() {}

    void Socket()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            logMessage(Fatal, "socket error:%s", strerror(errno));
            exit(SOCKET_ERROR);
        }
        logMessage(Debug, "socket success");

        int opt = 1;
        int ret = setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
        if (ret < 0)
        {
            logMessage(Fatal, "setsockopt error:%s", strerror(errno));
            exit(SETSOCKOPT_ERROR);
        }
        logMessage(Debug, "socket setsockopt success ");
    }

    void Bind(const uint16_t &port, const std::string &ip = "")
    {
        struct sockaddr_in addr;
        memset(&addr, 0, sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        if (ip == "")
        {
            addr.sin_addr.s_addr = htonl(INADDR_ANY);
        }
        else
        {
            addr.sin_addr.s_addr = inet_addr(ip.c_str());
        }

        int ret = bind(_sockfd, (struct sockaddr *)&addr, sizeof(addr));
        if (ret < 0)
        {
            logMessage(Fatal, "bind error:%s", strerror(errno));
            exit(BIND_ERROR);
        }
        logMessage(Info, "bind success");
    }

    void Listen(int backlog = default_backlog)
    {
        int ret = listen(_sockfd, backlog);
        if (ret < 0)
        {
            logMessage(Fatal, "listen error:%s", strerror(errno));
            exit(LISTEN_ERROR);
        }
        logMessage(Info, "listen success");
    }

    int Accept(std::string *ip, uint16_t *port)
    {
        struct sockaddr_in addr;
        memset(&addr, 0, sizeof(addr));
        socklen_t len = sizeof(addr);
        int new_sockfd = accept(_sockfd, (struct sockaddr *)&addr, &len);
        if (new_sockfd < 0)
        {
            logMessage(Warning, "accept error:%s", strerror(errno));
            return -1;
        }
        logMessage(Info, "accept success:%d", new_sockfd);
        *ip = inet_ntoa(addr.sin_addr);
        *port = ntohs(addr.sin_port);
        return new_sockfd;
    }

    void Connect(const std::string &ip, const uint16_t &port)
    {
        struct sockaddr_in addr;
        memset(&addr, 0, sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        addr.sin_addr.s_addr = inet_addr(ip.c_str());

        int ret = connect(_sockfd, (struct sockaddr *)&addr, sizeof(addr));
        if (ret < 0)
        {
            logMessage(Fatal, "connect error:%s", strerror(errno));
            exit(CONNECT_ERROR);
        }
        logMessage(Info, "connect success");
    }

    int Fd()
    {
        return _sockfd;
    }

    void Close()
    {
        if (_sockfd != default_fd)
            close(_sockfd);
    }

    // q : 存在线程安全问题吗？    a : 不会，因为每个线程都有自己的栈空间，所以不会有线程安全问题
    std::string Recv(int newsockfd)
    {
        char buf[1024] = {0};
        int ret = recv(newsockfd, buf, sizeof(buf) - 1, 0);
        if (ret < 0)
        {
            logMessage(Error, "recv error:%s", strerror(errno));
            return "";
        }
        else if (ret == 0)
        {
            logMessage(Info, "peer shutdown");
            return "";
        }
        else
        {
            buf[ret] = '\0';
            logMessage(Info, "recv success : %s", buf);
            return buf;
        }
    }
    bool Send(int newsockfd, const std::string &buf)
    {
        int ret = send(newsockfd, buf.c_str(), buf.size(), 0);
        if (ret < 0)
        {
            logMessage(Error, "send error:%s", strerror(errno));
            return false;
        }
        else
        {
            logMessage(Info, "send success : %s", buf.c_str());
            return true;
        }
    }

    std::string Recv()
    {
        char buf[1024] = {0};
        int ret = recv(_sockfd, buf, sizeof(buf) - 1, 0);
        if (ret < 0)
        {
            logMessage(Error, "recv error:%s", strerror(errno));
            return "";
        }
        else if (ret == 0)
        {
            logMessage(Info, "peer shutdown");
            return "";
        }
        else
        {
            buf[ret] = '\0';
            logMessage(Info, "recv success : %s", buf);
            return buf;
        }
    }

    bool Send(const std::string &buf)
    {
        int ret = send(_sockfd, buf.c_str(), buf.size(), 0);
        if (ret < 0)
        {
            logMessage(Error, "send error:%s", strerror(errno));
            return false;
        }
        else
        {
            logMessage(Info, "send success : %s", buf.c_str());
            return true;
        }
    }

private:
    int _sockfd;
};
